//路由鉴权:鉴权，项目当中的路由访问权限设置
import { ref } from 'vue'
import router from '@/router'
import * as NProgress from 'nprogress';
import 'nprogress/nprogress.css'; // 引入样式
import { RouteLocationRaw } from 'vue-router';

//获取用户相关的小仓库内部token数据，判断用户是否登录成功
import useUserStore from "./store/modules/user";
import pinia from './store';
const UserState = useUserStore(pinia);
// 配置 NProgress
NProgress.configure({ showSpinner: false });
interface BreadcrumbItem {
    path: string;
    label: string;
}
export const Breadcrumb = ref<BreadcrumbItem[]>([]);
export const currentPath = ref<string>('');
export const routerPush = (to: RouteLocationRaw) => {
    router.push(to).catch((err) => err);
};

export const closeBreadcrumb = function (path: string) {
    //判断当前关闭的标签是否在面包屑中,返回值为索引
    const itemIndex = Breadcrumb.value.findIndex((item) => item.path === path);
    //在面包屑中存在该标签
    if (itemIndex !== -1) {
        //删除面包屑中该标签
        Breadcrumb.value.splice(itemIndex, 1);
        if (currentPath.value === path) {
            if (Breadcrumb.value.length > 0) {
                currentPath.value = Breadcrumb.value[Breadcrumb.value.length - 1].path;
            } else {
                routerPush('/home');
            }
        }
    }
};

//全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
    console.log("permisstion中的前置路由守卫",to,from,next);  
    NProgress.start();
    //获取token,去判断是否登录成功
    const token = UserState.token;
    //获取用户的名字
    const username = UserState.username;
    if (token) {
        if (to.path === '/login') {
            next({path: '/'});
        } else {
            //登录成功，访问除登录login的路由
            //有用户信息
            if(username){
                next();
            }else{
                //没有用户信息，调用获取用户信息接口
                try{ 
                    // 获取用户信息
                 await  UserState.userInfo()
                 next();
                }catch(error){
                    // token失效了，清除token
                    UserState.userLogout()
                    //跳转到登录页
                    next({path: '/login',query:{redirect: to.path}})
                }
            }
            next();
        }
    }else {
        //用户未登录
        if (to.path === '/login') {
            next();
        } else {
            next({path: '/login',query:{redirect: to.path}});
        }
    }
    
});

//面包屑标最大长度
const MAX_BREADCRUMB_LENGTH = 6;
//全局后置守卫
router.afterEach((to: any, from: any) => {
    console.log("permisstion中的后置路由守卫",to,from);
    NProgress.done();
    // 确保面包屑中不包含'/login'
    const breadCrumbWithoutLogin = Breadcrumb.value.filter((item) => item.path !== '/login');
    // 检查当前路径是否已存在且非登录页
    const isPathNew = !breadCrumbWithoutLogin.some((item) => item.path === to.path);
    // 更新当前路径
    currentPath.value = to.path;
    // 设置文档标题
    if (to.meta.title) {
        document.title = to.meta.title as string;
    }
    // 当前路径未存在于面包屑中且不是登录页时，处理面包屑
    if (isPathNew) {
        // 限制面包屑长度
        if (breadCrumbWithoutLogin.length >= MAX_BREADCRUMB_LENGTH) {
            breadCrumbWithoutLogin.shift(); // 移除最旧的面包屑
        }
        // 推入新路径
        breadCrumbWithoutLogin.push({ path: to.path, label: to.meta.title as string || to.path });
        // 更新面包屑状态
        Breadcrumb.value = breadCrumbWithoutLogin;
    }
});


